package sample.controller.todo;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.BeanMap;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class IndexController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger =
        Logger.getLogger(IndexController.class.getName());

    private static final Integer PAGE_COUNT = 5;
    
    @Override
    public Navigation run() {
        DatastoreService datastoreService =
            DatastoreServiceFactory.getDatastoreService();
        // 検索
        Query q = new Query("Todo"); // KIND：Todoを検索
        q.addSort("done"); // doneでソートする
        PreparedQuery pq = datastoreService.prepare(q);
        // 総件数(このメソッドが返す結果件数は最大1000なのでそれを越える場合、
        // 別の方法を考える
        Integer count = pq.countEntities();
        
        // ページング処理
        Integer page = asInteger("page");
        if (page == null || page < 0) page = 0;
        if (page != null && page * PAGE_COUNT >= count) page = page - 1;
        Integer offset = page * PAGE_COUNT;
        
        requestScope("count", count);
        requestScope("page", page);
        
        // データの取得処理
        List<Entity> result = pq.asList(
                FetchOptions.Builder.withOffset(offset) // オフセットを指定
                .limit(PAGE_COUNT));                    // リミットを指定
        
        // JSPで使えるように結果をBeanMapに詰め替え
        List<BeanMap> list = new ArrayList<BeanMap>();
        for (Entity e : result) {
            Entity category = null;
            try {
                // 親Entity(カテゴリ)を取得
                // Enity#getParentで親のキーを取得
                category = datastoreService.get(e.getParent());
            } catch (EntityNotFoundException e1) {
                e1.printStackTrace();
            }
            
            BeanMap m = new BeanMap();
            m.put("key", KeyFactory.keyToString(e.getKey()));
            m.put("category", category.getProperty("name"));
            m.put("content", e.getProperty("content"));
            Boolean done = (Boolean) e.getProperty("done");
            if (done) {
                m.put("done", "完了済");
            } else {
                m.put("done", "未");
            }
            list.add(m);
        }
        requestScope("list", list);
        return forward("index.jsp");
    }
}
